package in.iqing.view.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;
import in.iqing.app.R;
import in.iqing.base.BaseFragment;
import in.iqing.control.adapter.CategoryAdapter;
import in.iqing.control.api.ApiHelper;
import in.iqing.control.api.callback.CategoryListCallback;
import in.iqing.control.helper.IntentHelper;
import in.iqing.control.helper.LogHelper;
import in.iqing.model.bean.Category;
import in.iqing.view.activity.CategoryBookListActivity;
import in.iqing.view.activity.LatestUpdateActivity;
import in.iqing.view.activity.SearchBookListActivity;
import in.iqing.view.widget.SpacesItemDecoration;

/**
 * Created by ZuoShu on 15/7/3.
 */
public class CategoryFragment extends BaseFragment {
    @Bind(R.id.category_recycler)
    RecyclerView categoryRecycler;

    CategoryAdapter categoryAdapter;

    ExtCategoryCallback callback;

    private CategoryAdapter.OnCategoryClickListener categoryClickListener;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_category, null);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        initCategoryRecyclerView();
        loadCategories();
    }

    private void initCategoryRecyclerView() {
        categoryAdapter = new CategoryAdapter(getContext());
        categoryRecycler.setAdapter(categoryAdapter);
        categoryRecycler.setHasFixedSize(true);
        categoryRecycler.setLayoutManager(new GridLayoutManager(getContext()
                , getResources().getInteger(R.integer.category_column)));
        categoryRecycler.addItemDecoration(new SpacesItemDecoration(
                        getResources().getInteger(R.integer.category_column)
                        , getResources().getDimensionPixelSize(R.dimen.category_grid_horizontal_spacing)
                        , getResources().getDimensionPixelSize(R.dimen.category_grid_vertical_spacing))
        );
        categoryClickListener = new ExtCategoryClickListener();
        categoryAdapter.setListener(categoryClickListener);
    }

    private void loadCategories() {
        showLoading();
        callback = new ExtCategoryCallback();
        ApiHelper.getSingleton().getCategories(VOLLEY_TAG, callback);
    }

    @OnEditorAction(R.id.search_edit)
    public boolean onSearchEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (actionId) {
            case EditorInfo.IME_ACTION_SEARCH:
                String keyword = v.getText().toString();
                search(keyword);
                break;
            default:
                LogHelper.warn(TAG, "ime action:" + actionId);
                break;
        }
        return true;
    }

    @OnTextChanged(R.id.search_edit)
    public void onSearchTextChange(CharSequence s, int start, int before, int count) {
        // handle weird input method which has no actionSearch button
        // detect Enter
        if (!TextUtils.isEmpty(s) && (start - before) <= s.length() && s.charAt(start - before) == '\n') {
            search(String.valueOf(s.subSequence(start, before)));
        }
    }

    private void search(String keyword) {
        if (TextUtils.isEmpty(keyword)) {
            return;
        }
        Bundle data = new Bundle();
        data.putSerializable("keyword", keyword);
        IntentHelper.startActivity(CategoryFragment.this.getActivity(), SearchBookListActivity.class, data);
    }

    private class ExtCategoryCallback extends CategoryListCallback {

        @Override
        public void onSuccess(List<Category> categories) {
            // TODO add recent update category manually
            if (categories == null || categories.size() == 0) {
                showEmpty();
                return;
            }
            Category latestUpdate = new Category();
            latestUpdate.setId(Category.LATEST_UPDATE);
            List<Category> localCategories = new ArrayList<>();
            localCategories.add(latestUpdate);
            localCategories.addAll(categories);
            categoryAdapter.setCategories(localCategories);
            categoryAdapter.notifyDataSetChanged();
            showContent();
        }

        @Override
        public void onFailure(int code, String msg) {
            showEmpty();
            LogHelper.warn(TAG, "load category error code:" + code + " msg:" + msg);
        }
    }

    private class ExtCategoryClickListener implements CategoryAdapter.OnCategoryClickListener {

        @Override
        public void onCategoryClick(Category category) {
            if (category.getId() == Category.LATEST_UPDATE) {
                IntentHelper.startActivity(CategoryFragment.this.getActivity(), LatestUpdateActivity.class);
            } else {
                Bundle data = new Bundle();
                data.putSerializable("category", category);
                IntentHelper.startActivity(CategoryFragment.this.getActivity(), CategoryBookListActivity.class, data);
            }
        }
    }

}
